<template>
	<view id="box">
		<view class="nav">
			<view class="nav_statusbar" :style="{height:statusBarHeight + 'rpx',width:'750rpx'}">
			</view>
			<view class="nav_box">
				<view class="m_b_14 m_r_8" style="flex-shrink: 0;">
					<up-image :show-loading="true" src="/static/images/index/index_position.png" width="20rpx"
						height="26rpx"></up-image>
					<!-- <up-icon name="/static/images/index/index_position.png" size="14"></up-icon> -->
				</view>
				<view class=" flex" @click="showCityPicker">
					<view class="m_r_8" style="max-width: 400rpx;">
						<text class="f_26_0 u-line-1">
							{{curAddress}}
						</text>
					</view>
					<view class="">
						<up-icon name="arrow-down-fill" size="14"></up-icon>
					</view>
				</view>

			</view>
		</view>
		<view class="" :style="{height:statusBarHeight + 76 +'rpx'}">

		</view>
		<view class="content" :style="{minHeight:contentHeight}">
			<view class="banner_box m_b_36">
				<up-swiper :list="banners" keyName="image" height="130" autoplay></up-swiper>
			</view>
			<view class="row1 m_b_40">
				<view class="row1_list ">
					<view class="row1_item" v-for="(item,index) in row1List" :key="index"
						@click="onClickRow1Item(item)">
						<view class="m_b_14">
							<up-image :show-loading="true" :src="item.icon" width="132rpx" height="138rpx"></up-image>
						</view>
						<view class="">
							<text class="f_28_0_b" style="color: #2B2B2B;">
								{{item.label}}
							</text>
						</view>

					</view>
				</view>
			</view>
			<view class="search_box m_b_20" @click="toSearch">
				<view class="search_input">
					<view class="flex" style="justify-content: center;">
						<view class="m_t_4">
							<up-icon name="search" color="#7E7D7D" size="18"></up-icon>
						</view>
						<text class="f_24_f" style="color: #808080;">
							请输入关键字
						</text>
					</view>
				</view>
			</view>
			<view class="row2">
				<view class="row2_header">
					<view class="row2_header_list flex_both">
						<view :class="['row2_header_item',item.state.isSel?'row2_header_item_acitve':'']"
							v-for="(item,index) in row2HeaderList" :key="index" @click="onClickRow2HeaderItem(item)">
							<view class="m_r_32 m_b_6">
								<text class="text">
									{{item.label}}
								</text>
							</view>
							<view class="m_b_2">
								<view class="" v-if="item.state.status == 0">
									<up-icon name="arrow-up-fill" size="9" color="#C5C5C5"></up-icon>
									<up-icon name="arrow-down-fill" size="9" color="#C5C5C5"></up-icon>
								</view>
								<view class="active_box" v-else-if="item.state.status == 1">
									<view class="">
										<up-icon name="arrow-up" size="9" color="#F7480B"></up-icon>
									</view>
								</view>
								<view class="active_box" v-else-if="item.state.status == 2">
									<view class="m_t_2">
										<up-icon name="arrow-down" size="9" color="#F7480B"></up-icon>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="row2_main">
					<scroll-view>
						<view class="row2_list">
							<view class="row2_item m_b_20" v-for="(item,index) in storeList" :key="index"
								@click="toDetail(item)">
								<view class="row2_item_row1 flex_both" style="align-items: flex-start;">
									<view class="row2_item_row1_left flex_both m_b_10">
										<view class="m_r_28">
											<up-image :show-loading="true" :src="item.shop_images.split(',')[0]"
												width="160rpx" height="146rpx"></up-image>
										</view>
										<view class="" style="width: 480rpx;">
											<view class="flex_both" style="align-items: flex-start;">
												<view class="m_b_24" style="width: 300rpx;">
													<text class="f_30_0_b">
														{{item.shop_name}}
													</text>
												</view>
												<view class="row2_item_row1_right"
													style="transform: translateY(-6rpx);">
													<text class="f_24_9" style="color: #939393;">
														{{item.distance}}
													</text>
												</view>
											</view>
											<view class="">
												<view class="flex">
													<view class="m_r_12 m_b_6">
														<up-image :show-loading="true"
															src="/static/images/index/clock_icon.png" width="28rpx"
															height="28rpx"></up-image>
													</view>
													<view class="">
														<text class="f_24_0" style="color: #737272;">
															{{item.begin_hour}} - {{item.end_hour}}
														</text>
													</view>
													<view class="f_26_0 m_l_12 m_r_12 m_t_6" style="color: #737272;">
														<text>
															|
														</text>
													</view>
													<view class="">
														<view class="" v-if="item.is_stop">
															<text class="f_24_0" style="color: #737272;"
																v-if="item.is_yingye">
																暂停营业
															</text>
														</view>
														<view class="" v-else>
															<text class="f_24_0" style="color: #FE450C;"
																v-if="item.is_yingye">
																营业中
															</text>
															<text class="f_24_0" style="color: #FA7B27;" v-else>
																已打烊
															</text>
														</view>
													</view>
												</view>
											</view>
											<view class="flex" style="align-items: flex-start;">
												<view class="m_r_6 m_b_10 m_l_6"
													style="width: 28rpx; height: 28rpx;flex-shrink: 0;">
													<up-image :show-loading="true"
														src="/static/images/index/position_icon.png" width="18rpx"
														height="24rpx"></up-image>
												</view>
												<view class="">
													<text class="f_24_0" style="color: #737272;">
														{{item.address}}
													</text>

												</view>
											</view>
										</view>
									</view>

								</view>
								<scroll-view class="m_b_16" :scroll-x="true" style="width: 672rpx; ">
									<view class="type_list flex " style="flex-wrap: nowrap;">
										<view class="flex m_r_10" style="flex-shrink: 0;"
											v-for="(item2, index2) in item.type_list" :key="index2">
											<view class="m_r_10">
												<up-icon name="/static/images/index/type_icon.png" size="15"></up-icon>
											</view>
											<view class="">
												<text class="f_26_0">
													{{item2.label}}
												</text>
											</view>
										</view>
										<!-- <up-checkbox-group v-model="item.typeCheackVal" placement="row" size="16"
											activeColor="#F76D11">
											<up-checkbox labelSize="12"
												:customStyle="{marginBottom: '8px',marginRight:'12rpx'}"
												v-for="(item2, index2) in item.type_list" :key="index2"
												:label="item2.label" :name="item2.label" :disabled="true">
											</up-checkbox>
										</up-checkbox-group> -->
									</view>
								</scroll-view>
								<view class="hr m_b_10 ">

								</view>
								<view class="row2_item_row2 flex_both">
									<view class="flex" style="align-items: flex-start;">
										<view class="m_r_10">
											<text class="f_24_0_b">
												评分
											</text>
										</view>
										<view class="m_t_6">
											<up-rate active-color="linear-gradient(to bottom, #FFFF59, #F9B900);"
												inactive-color="#b2b2b2" gutter="8" v-model="item.score"
												disabled></up-rate>
										</view>
									</view>
									<view class="" @click.stop="toOpenlocation(item)">
										<up-button type="primary">
											<view class="m_r_10 m_b_4">
												<!-- <up-image :show-loading="true"
													src="/static/images/index/index_row2_dh.png" width="22rpx"
													height="22rpx"></up-image> -->
												<up-icon name="/static/images/index/index_row2_dh.png"
													size="11"></up-icon>
											</view>
											<text class="f_24_f">
												导航
											</text>
										</up-button>
									</view>
								</view>
							</view>
						</view>
						<view class="empty_box" v-if="!loadShow &&storeList.length ==  0">
							<view class="">
								<up-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png">
								</up-empty>
							</view>
						</view>
						<view class="loading_box" v-if="loadShow">
							{{ loadMessage }}
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
		<Tabbar :activeTab="0"></Tabbar>
	</view>
	<!-- <up-picker :show="cityPickerShow" :columns="areaList" :defaultIndex="defaultIndex" confirmColor="#FA5A28"
		@confirm="onAreaPickerConfirm" keyName="fullname" @cancel="cityPickerShow = false"></up-picker> -->


	<up-picker ref="uCityPickerRef" :show="cityPickerShow" :columns="cityArr" keyName="name"
		@change="cityPickerChangeHandler" @cancel="cityPickerShow = false" @confirm="cityPickerConfirm"
		:defaultIndex="defaultIndex" confirmColor="#F76D11"></up-picker>
</template>
<script setup lang="ts">
	import { ref, reactive, getCurrentInstance } from "vue";
	import { onLoad, onShow, onReachBottom, onReady } from "@dcloudio/uni-app";
	import Tabbar from "@/components/user/tabbar.vue"
	import luoSwitch from '@/components/luo-switch/luo-switch.vue';
	import QQMapWX from '@/common/qqmap-wx-jssdk.js'
	const { proxy } = getCurrentInstance()
	const contentHeight = ref('100vh')
	const statusBarHeight = ref(88)
	const token = ref()
	const goto = (url) => {
		if (!token.value) {
			proxy.$gloab.gotoPage("/pages/login/index")
			return
		}
		proxy.$gloab.gotoPage(url)
	}
	onLoad(() => {
		uni.getSystemInfo({
			success: function (info) {
				statusBarHeight.value = (info.statusBarHeight) * 2
				contentHeight.value = `calc(100vh - ${statusBarHeight.value + 58}rpx - 26rpx - env(safe-area-inset-bottom) - 100rpx)`
			}
		});
		token.value = uni.getStorageSync('token');
		getBanner()
	})

	// 个人信息
	const userInfo = ref({
		avatar: ''
	})
	const getUserInfo = async () => {
		let res = await proxy.$http('my.getUserInfo')
		let data = res.data
		userInfo.value = data
	}

	const qqmapsdk = ref(null)
	onReady(() => {
		qqmapsdk.value = new QQMapWX({
			key: proxy.$config.txMapKey
		});
		getLoaction()
	})
	const longitude = ref()
	const latitude = ref()

	const getLoaction = () => {
		uni.getLocation({
			type: 'gcj02', // 返回可以用于uni.openLocation的经纬度
			success: function (res) {
				longitude.value = res.longitude
				latitude.value = res.latitude
				qqmapsdk.value.reverseGeocoder({
					location: {
						latitude: res.latitude,
						longitude: res.longitude
					},
					success: (res2) => {
						console.log(res2);
						// let data = res2.result.address_component
						// curAddress.value = res2.result.formatted_addresses.standard_address
						// console.log(data);
						// getDistrictByCityId(res2)
						// 获取区id
						getNowAreaByName(res2.result)
					},
					fail: (e) => {
						console.log(e, 'eee')
					}
				})

				// 获取附近房屋
			},
			fail: function (e) {
				// uni.setStorageSync('position_info', { code: 2, longitude: 0, latitude: 0 })
				console.log('获取位置信息失败：' + JSON.stringify(e));
			}
		});
	}
	const getNowAreaByName = async (e) => {

		let res = await proxy.$http("common.getNowAreaByName", { area_name: e.address_component.district, city_name: e.address_component.city })
		let data = res.data
		curAddress.value = data.province.name + '-' + data.cityInfo.name + '-' + data.areaInfo.name
		initCity(res.data)
	}
	// 区县相关
	const cityPickerShow = ref(false)
	const uCityPickerRef = ref(null)
	const rawCityData = ref([])
	const cityArr = ref([])
	const curAddress = ref('')
	const defaultIndex = ref([0, 3, 2])
	const positionInfo = ref({
		province_name: '',
		city_name: '',
		area_name: ''

	})
	const initCity = async (e) => {
		try {
			let res = await proxy.$http('common.getAreaAll')
			if (res.code === 1) {
				defaultIndex.value = []
				rawCityData.value = res.data
				positionInfo.value.province_name = e.province.name
				positionInfo.value.city_name = e.cityInfo.name
				positionInfo.value.area_name = e.areaInfo.name
				const provinceList = rawCityData.value.map(item => {
					return { name: item.name, id: item.id }
				})
				let provinceIndex = 0
				provinceList.forEach((v, index) => {
					if (v.id == e.province.id) {
						provinceIndex = index
						defaultIndex.value.push(index)
					}
				})
				const cityList = rawCityData.value[provinceIndex].children.map(item => {
					return { name: item.name, id: item.id }
				})
				let cityIndex = 0
				cityList.forEach((v, index) => {
					if (v.id == e.cityInfo.id) {
						defaultIndex.value.push(index)
						cityIndex = index
					}
				})
				const counties = rawCityData.value[provinceIndex].children[cityIndex].children.map(item => {
					return { name: item.name, id: item.id }
				})
				counties.forEach((v, index) => {
					if (v.id == e.areaInfo.id) {
						defaultIndex.value.push(index)
					}
				})
				console.log(defaultIndex.value);
				cityArr.value.push(provinceList, cityList, counties)
				initStore()
			} else {
				throw new Error(res.msg)
			}
		} catch (e) {
			uni.showToast({
				icon: 'none',
				title: e.message
			})
		}
	}
	const showCityPicker = () => {
		cityPickerShow.value = true
	}
	const cityPickerChangeHandler = (e) => {
		const { columnIndex, indexs } = e
		if (columnIndex === 0) {
			uCityPickerRef.value.setColumnValues(1, rawCityData.value[indexs[0]].children);
			uCityPickerRef.value.setColumnValues(2, rawCityData.value[indexs[0]].children[0].children);
		}
		if (columnIndex === 1) {
			uCityPickerRef.value.setColumnValues(2, rawCityData.value[indexs[0]].children[indexs[1]].children);
		}
	}
	const cityPickerConfirm = (e) => {
		const arr = []
		arr.push(e.value[0].name)
		arr.push(e.value[1].name)
		arr.push(e.value[2].name)
		curAddress.value = arr.join('-')
		positionInfo.value.province_name = e.value[0].name
		positionInfo.value.city_name = e.value[1].name
		positionInfo.value.area_name = e.value[2].name
		cityPickerShow.value = false
		initStore()
	}



	// const areaList = ref([[
	// 	{ id: 1, fullname: '蜀山区' },
	// 	{ id: 2, fullname: '包河区' },
	// 	{ id: 3, fullname: '高新区' },
	// 	{ id: 4, fullname: '瑶海区' },
	// ]])

	// const onAreaPickerConfirm = (e) => {
	// 	console.log(e.value[0]);
	// 	defaultIndex.value = [e.value[0].id]
	// 	curAddress.value = e.value[0].fullname
	// 	cityPickerShow.value = false
	// }

	// 服务类型相关

	// const getDistrictByCityId = (e) => {
	// 	qqmapsdk.value.getCityList({
	// 		success: function (res) {//成功后的回调
	// 			var cityId = res.result[1].filter(v => {
	// 				return v.id == e.ad_info.accode
	// 			})[0].id;
	// 			console.log(cityId , e);
	// 			//根据对应接口getCityList返回数据的Id获取区县数据（以北京为例）
	// 			qqmapsdk.value.getDistrictByCityId({
	// 				// 传入对应省份ID获得城市数据，传入城市ID获得区县数据,依次类推
	// 				id: cityId, //对应接口getCityList返回数据的Id，如：北京是'110000'
	// 				success: function (res) {//成功后的回调
	// 					console.log(res);
	// 					console.log('对应城市ID下的区县数据(以北京为例)：', res.result[0]);
	// 				},
	// 				fail: function (error) {
	// 					console.error(error);
	// 				},
	// 				complete: function (res) {
	// 					console.log(res);
	// 				}
	// 			});
	// 		},
	// 		fail: function (error) {
	// 			console.error(error);
	// 		},
	// 		complete: function (res) {
	// 			console.log(res);
	// 		}
	// 	})
	// }

	const toSelAddress = () => {
		// uni.chooseLocation({
		// 	longitude: longitude.value,
		// 	latitude: latitude.value,
		// 	success: function (res2) {
		// 		curAddress.value = res2.name
		// 		longitude.value = res2.longitude
		// 		latitude.value = res2.latitude
		// 		initStore()
		// 	}
		// })
	}
	// 轮播
	const banners = ref([
	]);
	const getBanner = async () => {
		let res = await proxy.$http('index.getBanner')
		let data = res.data
		banners.value = data
	}
	// 
	const row1List = ref([
		{ label: '扫码洗车', icon: '/static/images/index/index_row1_icon1.png', url: 'sCode' },
		{ label: '充值', icon: '/static/images/index/index_row1_icon2.png', url: '/pages/index/recharge' },
		{ label: '邀请码', icon: '/static/images/index/index_row1_icon3.png', url: 'code' },
	])
	const onClickRow1Item = async (e) => {
		if (e.url == 'sCode') {
			onSm()
			return
		}
		if (e.url == 'code') {
			let res = await proxy.$http('my.getUserInfo')
			let data = res.data
			if (data.is_marketing) {
				goto('/pages/my/marketingCode')
			} else {
				goto('/pages/my/myCode')
			}
			return
		}
		if (e.url) {
			goto(e.url)
		}
	}
	// 
	const row2HeaderList = ref([
		{
			label: '附近',
			index: 0,
			state: {
				isSel: false,
				status: 0
			}
		},
		{

			label: '距离',
			index: 1,
			state: {
				isSel: false,
				status: 0
			}
		},
		{

			label: '销量',
			index: 2,
			state: {
				isSel: false,
				status: 0
			}
		},
		{

			label: '排行',
			index: 3,
			state: {
				isSel: false,
				status: 0
			}
		},
	])
	const row2HeaderActiveIdx = ref()
	const onClickRow2HeaderItem = (e) => {
		resetRow2Header(e)
		row2HeaderActiveIdx.value = e.index
		switch (e.state.status) {
			case 0:
				row2HeaderList.value[e.index].state.isSel = true;
				row2HeaderList.value[e.index].state.status = 1;
				break;
			case 1:
				row2HeaderList.value[e.index].state.isSel = true;
				row2HeaderList.value[e.index].state.status = 2;
				break;
			case 2:
				row2HeaderList.value[e.index].state.isSel = false;
				row2HeaderList.value[e.index].state.status = 0;
				break;
		}
		initStore()
	}
	const resetRow2Header = (e) => {
		row2HeaderList.value.forEach((v, index) => {
			if (index != e.index) {
				v.state.isSel = false;
				v.state.status = 0;
			}
		})

	}
	// 门店列表
	const page = ref(1)
	const loadShow = ref(false)
	const loadMessage = ref('加载中')
	onReachBottom(() => {
		if (loadShow.value == true) return
		page.value = ++page.value;
		loadShow.value = true;
		setTimeout(() => {
			getShopList()
		}, 1000)
	})
	const storeList = ref([])

	const getShopList = async () => {
		if (loadMessage.value == '没有更多了') {
			loadShow.value = true;
			setTimeout(() => {
				loadShow.value = false;
			}, 200)
			return
		}
		let params = {
			sort_key: '',
			sort_type: ''
		}
		if (row2HeaderActiveIdx.value || row2HeaderActiveIdx.value == 0) {
			params = {
				sort_key: row2HeaderActiveIdx.value + 1,
				sort_type: row2HeaderList.value[row2HeaderActiveIdx.value].state.status == 1 ? 'asec' : 'desc'
			}
		}
		let res = await proxy.$http('index.getShopList', { page: page.value, lat: latitude.value, lng: longitude.value, ...positionInfo.value, ...params })
		let data = res.data.data
		if (res.code == 1) {
			if (data.length == 0) {
				loadMessage.value = "没有更多了"
			} else {
				data.forEach(function (v) {
					if (v.cartypesName) {
						let arr = v.cartypesName.split(',')
						v.type_list = []
						v.typeCheackVal = []
						arr.forEach(v2 => {
							v.type_list.push({ label: v2, val: 1 })
							v.typeCheackVal.push(v2)
						})
					} else {
						v.type_list = []
					}
				});
				storeList.value.push(...data)
			}
		} else {
			loadMessage.value = "加载出错"
		}
		setTimeout(() => {
			loadShow.value = false;
		}, 200)
		console.log(res);
	}
	const initStore = () => {
		page.value = 1
		loadMessage.value = '加载中'
		storeList.value = []
		getShopList()
	}

	const toDetail = (e) => {
		goto(`/pages/index/storeDetail?id=${e.shop_id}`)
	}

	// 导航
	const toOpenlocation = (e) => {
		if (!e.lat || !e.lng) {
			uni.$u.toast('坐标缺失')
			return
		}
		uni.openLocation({
			// 目标位置的经纬度
			latitude: parseFloat(e.lat),
			longitude: parseFloat(e.lng),
			// 目标位置的名称
			name: e.shop_name,
			// 目标位置的详细地址
			address: e.address,
			// 地图缩放比例
			scale: 18,
			// 调用成功时的回调函数
			success: function (res) {
				console.log('调用成功：', res)
			},
			// 调用失败时的回调函数
			fail: function (res) {
				console.log('调用失败：', res)
			},
			// 调用完成时的回调函数
			complete: function (res) {
				console.log('调用完成：', res)
			}
		})
	}
	// 扫码
	const onSm = () => {
		uni.scanCode({
			success: (res) => {
				// const BoardNo = encodeURIComponent(that.result1)
				goto('/' + res.path)
				console.log('条码类型：' + res.scanType);
				console.log('条码内容：' + res.result);
			},
			fail: (err) => {
				console.error('扫码失败：', err);
			}
		});
	}
	const toSearch = () => {
		goto(`/pages/index/search?longitude=${longitude.value}&latitude=${latitude.value}&positionInfo=${JSON.stringify(positionInfo.value)}`)
	}
</script>
<style lang="scss" scoped>
	#box {
		background: #F7F8FC;
	}

	.nav {
		position: fixed;
		left: 0;
		top: 0;
		background: #F7F8FC;
		z-index: 9;

		.nav_box {
			.nav_main {
				display: flex;
				align-items: center;
			}
		}
	}


	.content {
		padding: 0 20rpx;
		padding-top: 10rpx;

		.row1 {
			padding: 0 18rpx;

			.row1_list {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.row1_item {
					display: flex;
					flex-direction: column;
					align-items: center;
					flex-shrink: 0;
				}
			}
		}

		.row2 {

			.row2_header {
				.row2_header_list {
					.row2_header_item {
						width: 167rpx;
						height: 59rpx;
						background: #FFFFFF;
						border-radius: 10rpx;
					}

					.row2_header_item {
						width: 167rpx;
						height: 59rpx;
						background: #E5E2E2;
						border-radius: 10rpx;
						display: flex;
						align-items: center;
						justify-content: center;

						.text {
							font-size: 30rpx;
							color: #000000;
						}
					}

					.row2_header_item_acitve {
						background: #FD9125 !important;

						.text {
							color: white !important;
						}

						.active_box {
							width: 24rpx;
							height: 24rpx;
							background: #EFF0F4;
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
						}

					}
				}
			}

			.row2_main {
				padding: 20rpx 0;
				overflow: auto;

				.row2_list {
					.row2_item {
						padding: 20rpx;
						width: 672rpx;
						background: #FFFFFF;
						box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
						border-radius: 10rpx;

						::v-deep.row2_item_row2 .u-button {
							width: 143rpx;
							height: 47rpx;
							background: linear-gradient(90deg, #F7A52F, #F97119);
							border-radius: 24rpx;
							border: 0;
						}
					}
				}
			}
		}
	}

	.hr {
		height: 2rpx;
		background: #F3F3F1;
	}

	::v-deep.uicon-star-fill {
		background: linear-gradient(to bottom, #FFFF59, #F9B900);
		/*设置渐变的方向从左到右 颜色从ff0000到ffff00*/
		-webkit-background-clip: text;
		/*将设置的背景颜色限制在文字中*/
		-webkit-text-fill-color: transparent;
		/*给文字设置成透明*/
	}

	.search_box {
		width: 710rpx;
		height: 66rpx;
		background: #F7F8FC;

		.search_input {
			padding: 11rpx 0;
			background: #FFFFFF;
			box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
			border-radius: 34rpx;
			position: relative;

		}
	}

	::v-deep.u-checkbox__label-wrap {
		margin-bottom: 10rpx;
	}

	::v-deep.u-checkbox-group--row {
		flex-wrap: nowrap !important;
	}

	::v-deep.u-checkbox {
		flex-shrink: 0 !important;
	}
</style>